package com.xinyan.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xinyan.dto.ListPageParam;
import com.xinyan.plc.*;
import com.xinyan.service.MachineService;
import com.xinyan.util.XYUtil;
import com.xinyan.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import java.util.*;

@Validated
@RestController
@Slf4j
@RequestMapping("/plc")
public class MachineController {

    @Autowired
    private MachineService machineService;

    @Autowired
    private HandModeStartAndStop handModeStartAndStop;

    @Autowired
    private List<Integer> testIdList;

//    @PostMapping(path = "/start")
//    public ResponseEntity<String> start(@RequestBody List<String> list) {
//        log.info("========{}=======", list);
//        return ResponseEntity.ok("已成功启动主机:" + JSON.toJSONString(list));
//    }

    @GetMapping("/readListPageParam/{id}")
    public R<ListPageParam> readListPageParam(@PathVariable String id) {
        ListPageParam pageParam = machineService.readListPageParam(Integer.valueOf(id));
        return R.ok(pageParam);
    }

    /**
     * 处理切换手动模式请求
     *
     * @param ids
     * @return
     */
    @GetMapping("/hand")
    public R hand(@RequestParam(defaultValue = "1") List<Integer> ids) {
        log.info("========auto前端传入id：{}=======", JSON.toJSONString(ids));

        machineService.hand(testIdList);
        Map<String, Boolean> map = new HashMap<>();
        map.put("m32", true);
        map.put("m33", false);
        return R.ok(map);
    }

    /**
     * 处理切换到自动模式请求
     *
     * @param ids
     * @return
     */
    @GetMapping("/auto")
    public R auto(@RequestParam(defaultValue = "1") List<Integer> ids) {
        log.info("========auto前端传入id：{}=======", JSON.toJSONString(ids));
        machineService.auto(testIdList);
        Map<String, Boolean> map = new HashMap<>();
        map.put("m32", false);
        map.put("m33", true);
        return R.ok(map);
    }


    /**
     * 手动模式下启动
     *
     * @param ids
     * @return
     */
    @GetMapping("/handStart")
    public R handStart(@RequestParam @NotEmpty(message = "没有选择主机") List<Integer> ids) {
//        List<Integer> list = machineService.handStart(ids);
        log.info("========start前端传入id：{}=======", JSON.toJSONString(ids));
        List<Integer> list = machineService.handStart(testIdList);
        boolean empty = CollectionUtils.isEmpty(list);
        return empty ? R.fail("非手动模式，不可操作") : R.ok(list);
    }

    /**
     * 手动模式下停止
     *
     * @param ids
     * @return
     */
    @GetMapping("/handStop")
    public R handStop(@RequestParam @NotEmpty(message = "没有选择主机") List<Integer> ids) {
//        List<Integer> list = machineService.handStop(ids);
        log.info("=======stop：{}=======", JSON.toJSONString(ids));
        List<Integer> list = machineService.handStop(testIdList);
        boolean empty = CollectionUtils.isEmpty(list);
        return empty ? R.fail("非手动模式，不可操作") : R.ok(list);
    }

    /**
     * 设置变频器频率
     *
     * @param ids
     * @param frequency
     * @return
     */
    @GetMapping("/setFrequency")
    public R setFrequency(@RequestParam(defaultValue = "1") List<Integer> ids, @Min(value = 0, message = "频率设置不能小于0")
    @Max(value = 50, message = "频率设置不能大于50") @RequestParam float frequency) {
        log.info("========setFrequence传入ids:{},频率：{}======", ids, frequency);
//        machineService.setFrequency(ids, frequency);
        machineService.setFrequency(testIdList, frequency);
        return R.ok();
    }

    /**
     * 读取首页设置参数
     *
     * @param id
     * @return
     */
    @GetMapping("/readIndexParam")
    public R<IndexParam> readIndexParam(@RequestParam(defaultValue = "1") int id) {
        log.info("========readIndexParam:{}======", id);
        IndexParam indexParam = machineService.readIndexParam(id);
        return R.ok(indexParam);
    }

    @GetMapping("/readRunParam")
    public R<List<RunParam>> readRunParam(@RequestParam(defaultValue = "1") List<Integer> ids) {
        log.info("========readRunParam传入ids:{}======", ids);
//        List<RunParam> list = machineService.readRunParam(ids);
        List<RunParam> list = machineService.readRunParam(testIdList);
        return R.ok(list);
    }
    @GetMapping("/readRunParamById")
    public R<RunParam> readRunParamById(@RequestParam(defaultValue = "1") int id) {
        log.info("========readRunParamById 传入id:{}======", id);
//        List<RunParam> list = machineService.readRunParam(ids);
        RunParam runParam = machineService.readRunParamById(1);
        return R.ok(runParam);
    }

    @GetMapping("/readRepeatParam")
    public R<List<Map<String, String>>> readRepeatParam(@RequestParam(defaultValue = "1") List<Integer> ids) {
        log.info("========readRepeatParam传入ids:{}======", ids);
//        List<RepeatParam> repeatParams = machineService.readRepeatParam(ids);
        List<RepeatParam> repeatParams = machineService.readRepeatParam(testIdList);
        List<Map<String, String>> result = new ArrayList<>();
        repeatParams.forEach(e -> result.add(XYUtil.repeatParam2Map(e)));
        return R.ok(result);
    }

    @GetMapping("/readRepeatParamById")
    public R<RepeatParam> readRepeatParamById(@RequestParam(defaultValue = "1") int id) {
        log.info("========readRepeatParamById 传入id:{}======", id);
//        List<RepeatParam> repeatParams = machineService.readRepeatParam(ids);
        RepeatParam repeatParams = machineService.readRepeatParamById(1);
        return R.ok(repeatParams);
    }

    @PostMapping("/writeRepeatParamByMap")
    public R<List<Integer>> writeRepeatParamByMap(@RequestBody Map<String, String> mapParam) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String ids = requestAttributes.getRequest().getHeader("ids");
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        Map<Integer, RepeatParam> map = new HashMap<>();
        for (String id : list) {
            map.put(Integer.valueOf(id), XYUtil.map2RepeatParam(mapParam));
        }
        List<Integer> repeatParams = machineService.writeRepeatParam(map);

        return R.ok(repeatParams);
    }
    @PostMapping("/writeRepeatParamByJson")
    public R writeRepeatParamByJson(@RequestBody Map<String, String> mapParam) {
        log.info("============传入实体：{}",JSON.toJSONString(mapParam,true));
        String id = mapParam.get("id");
        RepeatParam repeatParam = JSON.parseObject(JSON.toJSONString(mapParam), RepeatParam.class);
        log.info("============转换后结果：{}",JSON.toJSONString(repeatParam,true));
        machineService.writeRepeatParamByEntity(repeatParam,Integer.valueOf(id));
        return R.ok(id);
    }

    /**
     * 自由参数
     *
     * @param repeatRunStopParam
     * @return
     */
    @PostMapping("/setRepeatParam")
    public R<List<Integer>> setRepeatParam(@RequestBody RepeatRunStopParam repeatRunStopParam) {
        List<Integer> repeatParams = machineService.setRepeatParam(repeatRunStopParam);

        return R.ok(repeatParams);
    }

    @PostMapping("/testMap")
    public R testMap(@RequestBody Map<String, String> map) {
        log.info(JSON.toJSONString(map, SerializerFeature.PrettyFormat));
        return R.ok();
    }

}
